<script setup lang="ts">
import { useAppStore } from '@/store';
import userRequest from '@/request/userRequest';
import Tools from '@/utils/tools';
import validate, { IValidator } from '@/utils/validate';
import Location from '@/utils/location';
import to from '@/utils/to';
import EquipRequest from '@/request/equipRequest';
import { navigate } from '@/utils/navigate';
import useToast from '@/hooks/useToast';

interface IProps {
  beeperCode: string;
  bindCallerInfo: IObtBindCallerInfoRes;
}

interface IState {
  show: boolean;
  receivingAddressList: IListShippingAddressesRes[];
  receivingAddressShow: boolean;
  placeholder: string;
  cascaderData: IBuildingTreeRes[];
  cascaderOptions: IBuildingTreeRes[];
  cascaderValue: string;
  cascaderSelectedOptions: IBuildingTreeRes[];
  params: {
    linkName?: string;
    phone: string;
    userAddress?: { [key: string]: string };
    [key: string]: any;
  };
}

const store = useAppStore();
const props = defineProps<IProps>();
const { showToast } = useToast();
const state = reactive<IState>({
  show: false,
  placeholder: '请选择住户地址',
  params: { phone: store.$state.userInfo.phone || '' },
  cascaderOptions: [],
  cascaderData: [],
  cascaderSelectedOptions: [],
  cascaderValue: '',
  receivingAddressList: [],
  receivingAddressShow: false,
});
const validators: IValidator<typeof state.params>[] = [
  { key: 'phone', name: '联系人电话', required: true, rule: /^(?:\+86)?1[3-9]\d{9}$/ },
  { key: 'linkName', name: '联系人', required: true },
];

onMounted(() => {
  // 用户新地址
  if (props.bindCallerInfo.addressType === 5) {
    fetchReceivingAddressInfo();
    return;
  }
  switch (props.bindCallerInfo.addressType) {
    case 4:
      state.placeholder = '请选择门牌号';
      fetchFloorTreeInformation({ parentId: props.bindCallerInfo.floorId });
      break;
    case 6:
      state.placeholder = '请选择层、门牌号';
      fetchFloorTreeInformation({ parentId: props.bindCallerInfo.unitId });
      break;
    case 7:
      state.placeholder = '请选择单元、层、门牌号';
      fetchFloorTreeInformation({ parentId: props.bindCallerInfo.buildId });
      break;
    case 8:
      state.placeholder = '请选择栋、单元、层、门牌号';
      fetchFloorTreeInformation({ villageId: props.bindCallerInfo.villageId });
      break;
  }
});

// 获取收货地址信息
const fetchReceivingAddressInfo = () => {
  userRequest.ListShippingAddress({ hasLoading: true }).then((res) => {
    state.receivingAddressList = res.data;
  });
};

// 获得单元层信息
const fetchFloorTreeInformation = (params: { parentId?: number; villageId?: number }) => {
  userRequest.BuildingTree(params).then((res) => {
    state.cascaderData = res.data;
    state.cascaderOptions = Tools.deEmptyChildrenCascader(res.data).map((item) => {
      if (props.bindCallerInfo.addressType === 4) {
        return item;
      }
      return { ...item, children: [] };
    });
  });
};

// 地区选择器完成事件
const handleCascaderFinish = (e: any) => {
  const { selectedOptions, value } = e.detail;
  state.cascaderSelectedOptions = selectedOptions;
  state.cascaderValue = value;
  state.show = false;
};

// 地区选择器选中事件
const handleCascaderChange = (e: any) => {
  const { tabIndex, selectedOptions, value } = e.detail;
  const insertData = Tools.findPathDFS<IBuildingTreeRes>(state.cascaderData, e.detail.value);
  if (!insertData) return;
  const index = state.cascaderData.findIndex((item) => item.id === insertData.id);
  state.cascaderValue = value;
  state.cascaderSelectedOptions = selectedOptions;
  if (tabIndex === 0) {
    state.cascaderOptions = Tools.deEmptyChildrenCascader(state.cascaderData).map((item) => {
      return { ...item, children: [] };
    });
    state.cascaderOptions[index].children = insertData.children;
  }
};

// 打开地图选取地址
const handleChooseLocation = async () => {
  const chooseRes = await uni.chooseLocation();
  if (!chooseRes) return;
  const location = await Location.reverseGeocoderLocation({ lat: chooseRes.latitude, lng: chooseRes.longitude });
  if (!location) return;
  const { address_component, formatted_addresses } = location;
  state.params.userAddress = {
    provinceName: address_component.province,
    cityName: address_component.city,
    areaName: address_component.district,
    streetName: address_component.street,
    latitude: chooseRes.latitude.toString(),
    longitude: chooseRes.longitude.toString(),
    address: formatted_addresses.recommend,
  };
  state.receivingAddressShow = false;
};

// 收货地址列表点击事件
const handleReceivingAddressListClick = (data: IListShippingAddressesRes) => {
  const { provinceName, cityName, areaName, streetName, latitude, longitude, houseNumber, villageName, buildName, unitName, floorName } = data;
  state.params.userAddress = { provinceName, cityName, areaName, streetName, villageName, buildName, unitName, floorName, houseNumber, latitude: latitude.toString(), longitude: longitude.toString() };
  state.receivingAddressShow = false;
};

// 绑定呼叫器点击事件
const handleBindBeeperClick = async () => {
  const { addressType } = props.bindCallerInfo;
  if (addressType === 4) {
    state.params.houseNumberId = state.cascaderValue;
    if (state.cascaderSelectedOptions.length > 0) {
      state.params.houseNumber = state.cascaderSelectedOptions[0].name;
    }
    validators.push({ key: 'houseNumberId', name: '住户地址', required: true });
  }
  if (addressType === 5) {
    validators.push({ key: 'userAddress', name: '收货地址', required: true });
  }
  if (addressType === 6) {
    if (state.cascaderSelectedOptions.length < 2) {
      showToast('住户地址请选择到门牌号');
      return;
    }
    if (state.cascaderSelectedOptions.length > 0) {
      state.params.floorId = state.cascaderSelectedOptions[0].id;
      state.params.floorName = state.cascaderSelectedOptions[0].name;
      state.params.houseNumber = state.cascaderSelectedOptions[1].name;
      state.params.houseNumberId = state.cascaderSelectedOptions[1].id;
    }
    validators.push({ key: 'houseNumberId', name: '住户地址', required: true });
  }
  if (addressType === 7) {
    if (state.cascaderSelectedOptions.length < 3) {
      showToast('住户地址请选择到门牌号');
      return;
    }
    if (state.cascaderSelectedOptions.length > 0) {
      state.params.unitId = state.cascaderSelectedOptions[0].id;
      state.params.unitName = state.cascaderSelectedOptions[0].name;
      state.params.floorId = state.cascaderSelectedOptions[1].id;
      state.params.floorName = state.cascaderSelectedOptions[1].name;
      state.params.houseNumber = state.cascaderSelectedOptions[2].name;
      state.params.houseNumberId = state.cascaderSelectedOptions[2].id;
    }
    validators.push({ key: 'houseNumberId', name: '住户地址', required: true });
  }
  if (addressType === 8) {
    if (state.cascaderSelectedOptions.length < 4) {
      showToast('住户地址请选择到门牌号');
      return;
    }
    if (state.cascaderSelectedOptions.length > 0) {
      state.params.buildId = state.cascaderSelectedOptions[0].id;
      state.params.buildName = state.cascaderSelectedOptions[0].name;
      state.params.unitId = state.cascaderSelectedOptions[1].id;
      state.params.unitName = state.cascaderSelectedOptions[1].name;
      state.params.floorId = state.cascaderSelectedOptions[2].id;
      state.params.floorName = state.cascaderSelectedOptions[2].name;
      state.params.houseNumber = state.cascaderSelectedOptions[3].name;
      state.params.houseNumberId = state.cascaderSelectedOptions[3].id;
    }
    validators.push({ key: 'houseNumberId', name: '住户地址', required: true });
  }
  const isValid = validate(state.params, validators);
  if (!isValid) return;
  const [err] = await to(EquipRequest.BindCallerDevice({ ...state.params, equipId: props.bindCallerInfo.equipId, hasLoading: true }));
  if (err) return;
  if (props.bindCallerInfo.beeperType === 1) store.$patch({ beeperId: props.bindCallerInfo.relationId });
  showToast(props.bindCallerInfo.beeperType === 1 ? '绑定呼叫器成功' : '绑定呼叫器成功,请等待主用户同意', props.bindCallerInfo.beeperType === 1 ? 'success' : 'none').then(() => {
    setTimeout(() => {
      navigate({ url: '/pages/home/index', type: 'switchTab' });
    }, 1000);
  });
};
</script>

<template>
  <view class="bg-white c-pd c-br py-12px mb-12px">
    <view class="fw-bold">收货地址信息</view>
    <van-divider />
    <van-cell title="住户地址" required is-link v-if="[4, 6, 7, 8].some((item) => item === props.bindCallerInfo.addressType)" @click="state.show = true">
      <view class="c-text-color-grey text-align-left" v-if="state.cascaderSelectedOptions.length === 0">{{ state.placeholder }}</view>
      <view class="c-color-black text-align-left" v-else>{{ state.cascaderSelectedOptions.map((item: IBuildingTreeRes) => item.name).join('-') }}</view>
    </van-cell>
    <van-cell title="收货地址" required is-link v-if="props.bindCallerInfo.addressType === 5" @click="state.receivingAddressShow = true">
      <view class="c-text-color-grey text-align-left" v-if="!state.params.userAddress">请选择收货地址</view>
      <view class="c-color-black text-align-left" v-else>{{
        state.params.userAddress.villageName
          ? `${state.params.userAddress.villageName}${state.params.userAddress.villageName}${state.params.userAddress.buildName}${state.params.userAddress.unitName}${state.params.userAddress.floorName}${state.params.userAddress.houseNumber}`
          : state.params.userAddress.address
      }}</view>
    </van-cell>
    <van-field clearable clickable :value="state.params.linkName" label="联系人" placeholder="请输入联系人" required @change="state.params.linkName = $event.detail" />
    <van-field clearable clickable :value="state.params.phone" label="电话" placeholder="请输入联系人电话" required @change="state.params.phone = $event.detail" />
  </view>

  <view class="mt-12px">
    <van-button type="primary" :color="'#ffc300'" block @click="handleBindBeeperClick"> 绑定呼叫器 </van-button>
  </view>

  <van-popup :show="state.show" round position="bottom" @close="state.show = false">
    <van-cascader
      :active-color="'#ffc300'"
      :show="state.show"
      :value="state.cascaderValue"
      :field-names="{ text: 'name', value: 'id' }"
      :title="state.placeholder"
      :options="state.cascaderOptions"
      @close="state.show = false"
      @finish="handleCascaderFinish"
      @change="handleCascaderChange"
    />
  </van-popup>
  <van-popup :show="state.receivingAddressShow" round position="bottom" @close="state.receivingAddressShow = false">
    <view class="c-pd">
      <view class="c-text-14 text-align-center fw-bold mb-12px">请选择或新增地址</view>
      <scroll-view scroll-y enhanced class="overflow-hidden min-h-200px max-h-400px">
        <view v-for="(item, index) in state.receivingAddressList" :key="index" @click="handleReceivingAddressListClick(item)">
          <view class="fw-bold c-text-14 mb-8px">{{ `${item.address}${item.villageName || ''}${item.buildName || ''}${item.unitName || ''}${item.floorName || ''}${item.houseNumber || ''}` }}</view>
          <view class="c-text-color-grey">
            <text>{{ item.linkName }}-</text>
            <text>{{ item.phone }}</text>
          </view>
          <van-divider v-if="index !== state.receivingAddressList.length - 1" />
        </view>
      </scroll-view>
      <view class="mt-12px">
        <van-button type="primary" :color="'#ffc300'" block @click="handleChooseLocation"> 新增地址 </van-button>
      </view>
    </view>
  </van-popup>
</template>
